package com.dragon.framework.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.util.ContentCachingRequestWrapper;

import java.io.IOException;
import java.util.Objects;

/**
 * Repeatable过滤器
 *
 * @author dragon
 * @version 1.0
 * @date 2024/9/26 16:52
 */
public class RepeatableFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        if (request instanceof HttpServletRequest) {
            // 重写JSON提交数据
            if (StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
                requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
            }
            // 重写表单数据，貌似不是必须的
            if (StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.MULTIPART_FORM_DATA_VALUE)) {
                requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
            }
        }

        chain.doFilter(Objects.requireNonNullElse(requestWrapper, request), response);
    }

    @Override
    public void destroy() {

    }

}
